<template>
  <Row>
    <div class="dt">
      <vc-config-provider :accessToken="accessToken">
        <vc-viewer @ready="onViewerReady" :show-credit="false">
          <!--洪水实验 -->
          <!-- <vc-analysis-flood
            @ready="ready"
            ref="flood"
            :min-height="minHeight.value"
            :max-height="maxHeight"
            :speed="speed"
            :polygon-hierarchy="polygonHierarchy"
          /> -->
          <!-- <vc-entity @dblclick="dblclick" :position="[103.319673, 31.427]" :label="label">
            <vc-graphics-point color="red" :pixel-size="8" />
          </vc-entity> -->
          <!-- 天地图服务 -->
          <vc-layer-imagery :sort-order="20">
            <vc-imagery-provider-tianditu
              map-style="cva_c"
              token="758974b67a98c41bfdfa44822f931633"
            ></vc-imagery-provider-tianditu>
          </vc-layer-imagery>
          <vc-layer-imagery :sort-order="10">
            <vc-imagery-provider-tianditu
              :map-style="mapStyle"
              token="758974b67a98c41bfdfa44822f931633"
              ref="provider"
            ></vc-imagery-provider-tianditu>
          </vc-layer-imagery>
          <!-- 贴地 -->
          <!-- <vc-terrain-provider-cesium /> -->
          <div class="disno">
            <vc-drawings
              @ready="drawingsReadyDefault"
              ref="drawingsRef"
              position="bottom-left"
              :clamp-to-ground="clampToGround"
              @draw-evt="drawEvt"
          /></div>
        </vc-viewer>
      </vc-config-provider>
    </div>
    <Row>
      <div class="z">
        <collapse v-model:activeKey="activeKey" accordion>
          <collapse-panel key="1" header="洪水实验">
            <div>
              <p>实验参数</p>
              <div>
                <Form :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <FormItem label="洪水高度：">
                    <Input v-model:value="maxHeight" label="hhhh " placeholder="请输入淹没高度" />
                  </FormItem>
                </Form>
                <Button type="primary" shape="round" @click="pause">{{
                  pausing.pausing ? '开始' : '暂停'
                }}</Button>
                <Button type="primary" shape="round" @click="stop">结束</Button>
              </div>
            </div>
          </collapse-panel>
          <collapse-panel key="2" header="手动绘制洪水淹没范围">
            <!-- 修改定位 和 位置偏移 -->
            <div>是否贴地绘制<Switch v-model:checked="clampToGround" /></div>
            <template v-for="(item, index) in draws" :key="index">
              <Button @click="buttonclick(item.name)" block size="large"> {{ item.tip }}</Button>
            </template>
          </collapse-panel>
          <collapse-panel key="3" header="其他实验">
            <p>to do~~~</p>
          </collapse-panel>
        </collapse>
      </div>
    </Row>
  </Row>
</template>

<script>
import { defineComponent, ref, reactive, toRaw } from 'vue';
import {
  Button,
  Row,
  Col,
  Collapse,
  CollapsePanel,
  Input,
  Form,
  FormItem,
  Switch,
} from 'ant-design-vue';
import * as zzymap from 'cesium';
import axios from 'axios';
export default defineComponent({
  name: 'Analysis',
  components: { Button, Row, Col, Collapse, CollapsePanel, Input, Form, FormItem, Switch },
  setup() {
    //任务模块
    const items = ['洪水实验', '其他实验'];
    const activeKey = ref(['1']);
    const Viewer = ref();
    const onViewerReady = ({ Cesium, viewer, dcViewer }) => {
      console.log(Cesium, 'Cesium', viewer.scene.imageryLayers);
      //添加图层
      // const tdt_key = '758974b67a98c41bfdfa44822f931633';
      // var img_tdt = new Cesium.WebMapTileServiceImageryProvider({
      //   url: 'http://t0.tianditu.com/img_w/wmts?tk=' + tdt_key,
      //   layer: 'img',
      //   style: 'default',
      //   tileMatrixSetID: 'w',
      //   format: 'tiles',
      //   maximumLevel: 18,
      // });
      // var img_cia = new Cesium.WebMapTileServiceImageryProvider({
      //   url: 'http://t0.tianditu.gov.cn/cia_w/wmts?tk=' + tdt_key,
      //   layer: 'cia',
      //   style: 'default',
      //   tileMatrixSetID: 'w',
      //   format: 'tiles',
      //   maximumLevel: 18,
      // });
      // var layers = viewer.scene.imageryLayers;
      // layers.addImageryProvider(img_tdt);
      // layers.addImageryProvider(img_cia);

      Viewer.value = viewer;
      viewer.scene.globe.depthTestAgainstTerrain = true;
      //去除点击四角形
      // viewer.selectionIndicator = false;
      const boundingSphere = new Cesium.BoundingSphere(
        Cesium.Cartesian3.fromDegrees(120.55538, 31.87532, 100),
        15000,
      );
      // 定位到初始位置
      viewer.camera.flyToBoundingSphere(boundingSphere, {
        // 动画，定位到初始位置的过渡时间，设置成0，就没有动画
        duration: 2,
      });
      //假数据
      const pointInfo = [
        {
          id: '392f7fbb-ae25-4eef-ac43-58fd91148d1f',
          latitude: '31.87532',
          longitude: '120.55538',
          psName: '有限公司1',
        },
        {
          id: '0278a88c-b4f4-4d64-9ccb-65831b3fb19d',
          latitude: '31.991057',
          longitude: '120.700713',
          psName: '有限公司2',
        },
        {
          id: '248f6853-2ced-4aa6-b679-ea6422a5f3ac',
          latitude: '31.94181',
          longitude: '120.51517',
          psName: '有限公司3',
        },
        {
          id: 'F8DADA95-A438-49E1-B263-63AE3BD7DAC4',
          latitude: '31.97416',
          longitude: '120.56132',
          psName: '有限公司4',
        },
        {
          id: '9402a911-78c5-466a-9162-d5b04d0e48f0',
          latitude: '31.91604',
          longitude: '120.57771',
          psName: '有限公司5',
        },
        {
          id: 'EB392DD3-6998-437F-8DCB-F805AD4DB340',
          latitude: '31.88727',
          longitude: '120.48887',
          psName: '有限公司6',
        },
      ];
      const foo = () => {
        return new URL('./1.png', import.meta.url);
      };
      console.log(foo(), ' 图片url');
      const _textColor = 'rgb(213, 24, 42)';
      //清除上一个标记点
      // viewer.entities.removeAll();
      //开始添加实例点
      pointInfo.forEach((pointObj) => {
        viewer.entities.add({
          name: pointObj.psName,
          code: pointObj.id,
          id: pointObj.id,
          position: Cesium.Cartesian3.fromDegrees(pointObj.longitude * 1, pointObj.latitude * 1),
          label: {
            // show: false,
            text: pointObj.psName,
            font: '12px monospace',
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            // fillColor: Cesium.Color.LIME,
            fillColor: Cesium.Color.fromCssColorString(_textColor),
            outlineWidth: 4,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 垂直方向以底部来计算标签的位置
            pixelOffset: new Cesium.Cartesian2(0, -20), // 偏移量
          },
          billboard: {
            image: foo().pathname,
            width: 18,
            height: 24,
          },
        });
      });
      //监听地图点击
      // const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      // handler.setInputAction((click) => {
      //   console.log('鼠标点击事件', click);
      // }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      //请求gojson数据
      const data = new URL('./data.geojson', import.meta.url).href;

      new Cesium.GeoJsonDataSource().load(data).then((dataSource) => {
        console.log(dataSource, 'dataSource');
        viewer.dataSources.add(dataSource);
        dataSource.clustering.enabled = true;
        dataSource.clustering.pixelRange = 60;
        dataSource.clustering.minimumClusterSize = 2;
        dataSource.entities.values.forEach((entity) => {
          // 将点拉伸一定高度，防止被地形压盖
          entity.position._value.z += 50.0;
          // 使用大小为64*64的icon，缩小展示poi
          entity.billboard = {
            image: new URL('./3.png', import.meta.url).href,
            width: 32,
            height: 32,
          };
          entity.label = {
            text: '我是莎莎',
            font: 'bold 20px Microsoft YaHei',
            fillColor: Cesium.Color.fromCssColorString(_textColor),
            // fillColor:Cesium.Color.fromCssColorString(_textColor),
            // 竖直对齐方式
            verticalOrigin: Cesium.VerticalOrigin.CENTER,
            // 水平对齐方式
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            // 偏移量
            pixelOffset: new Cesium.Cartesian2(15, 0),
          };
        });
        //添加监听函数
        dataSource.clustering.clusterEvent.addEventListener((clusteredEntities, cluster) => {
          //去掉默认的聚合数字
          cluster.label.show = false;
          cluster.billboard.show = true;
          cluster.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
          console.log(clusteredEntities, 'clusteredEntities');
          if (clusteredEntities.length >= 20) {
            cluster.billboard.image = combineIconAndLabel(
              './icons/cluster_4.png',
              clusteredEntities.length,
              64,
            );
            cluster.billboard.width = 72;
            cluster.billboard.height = 72;
          } else if (clusteredEntities.length >= 12) {
            cluster.billboard.image = combineIconAndLabel(
              './icons/cluster_3.png',
              clusteredEntities.length,
              64,
            );
            cluster.billboard.width = 56;
            cluster.billboard.height = 56;
          } else if (clusteredEntities.length >= 8) {
            cluster.billboard.image = combineIconAndLabel('./1.png', clusteredEntities.length, 64);
            cluster.billboard.width = 48;
            cluster.billboard.height = 48;
          } else {
            cluster.billboard.image = combineIconAndLabel(
              './icons/cluster_1.png',
              clusteredEntities.length,
              64,
            );
            cluster.billboard.width = 40;
            cluster.billboard.height = 40;
          }
        });
        const combineIconAndLabel = (url, label, size) => {
          let canvas = document.createElement('canvas');
          canvas.width = size;
          canvas.height = size;
          let ctx = canvas.getContext('2d');
          let newurl = new URL(url, import.meta.url).href;
          let promise = new Cesium.Resource.fetchImage(newurl).then((image) => {
            // 异常判断
            try {
              ctx.drawImage(image, 0, 0);
            } catch (e) {
              console.log(e);
            }
            // 渲染字体
            // font属性设置顺序：font-style, font-variant, font-weight, font-size, line-height, font-family
            ctx.fillStyle = Cesium.Color.WHITE.toCssColorString();
            ctx.font = 'bold 20px Microsoft YaHei';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText(label, size / 2, size / 2);
            return canvas;
          });
          return promise;
        };
      });
      console.log(dcViewer, 'dcViewer');
    };

    const ready = (e) => {
      console.log(e, 'ready');
    };
    let minHeight = ref(-1);
    let maxHeight = ref(3000);
    let speed = 2;
    //淹没多边形数据
    let polygonHierarchy = [
      [102.1, 29.5],
      [106.2, 29.5],
      [106.2, 33.5],
      [102.1, 33.5],
    ];
    const pausing = reactive({ pausing: true });
    const flood = ref();
    const start = () => {
      console.log(flood.value, 'flood');
      pausing.pausing = !pausing.pausing;
      flood.value.start();
    };
    const pause = () => {
      flood.value.pause();
      pausing.pausing = !pausing.pausing;
    };
    const stop = () => {
      flood.value.stop();
      pausing.pausing = !pausing.pausing;
    };
    const label = {
      text: '洪水实验',
      pixelOffset: [0, -30],
    };
    const accessToken =
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyMTUyMDlmMi1mYzMzLTQ5MDUtYTdmYS00YWZhYTE5NWNhY2MiLCJpZCI6OTc2NTQsImlhdCI6MTY1NTI3NTM3NH0.yQhWjhGbY-Ad8S9-T73vOSJSANGfmXblphhtCchKZ2s';
    const dblclick = (e) => {
      console.log(e, '用户双击了实例');
    };
    //手动绘制淹没范围
    const drawingsRef = ref('');
    const draws = [
      {
        name: 'polyline',
        tip: '开始绘制范围',
      },
      {
        name: 'clearAll',
        tip: '清除',
      },
    ];
    //开始绘画
    const buttonclick = (e) => {
      drawingsRef.value.toggleAction(e);
      if (e == 'clearAll') drawingsRef.value.clearAll();
    };
    const clampToGround = ref(false);
    const drawingsReadyDefault = ({ cesiumObject }) => {
      console.log(cesiumObject, 'cesiumObject ');
    };
    const t = ref();
    let newdata = ref(new Map());
    const datalist = ref([]);
    const drawEvt = (evt, viewer) => {
      clearTimeout(t.value);
      t.value = setTimeout(() => {
        const positionsDegreesArray = toRaw(evt.positionsDegreesArray);
        console.log(positionsDegreesArray, 'positionsDegreesArray');
        let data = positionsDegreesArray.map((e) => {
          return e.slice(0, 2);
        });
        newdata.value.set(data[0][0], data);
        // positionsDegreesArray.map((item, index) => {
        //   console.log(item, '数据的值');
        //   return [...item.slice(0, 2)];
        // });
        // if (positionsDegreesArray) floodlists.push(positionsDegreesArray.slice(0, 2));
        console.log(toRaw(newdata.value), 'newdata');
      }, 500);
    };
    return {
      onViewerReady,
      ready,
      minHeight,
      maxHeight,
      speed,
      polygonHierarchy,
      start,
      pause,
      stop,
      flood,
      pausing,
      label,
      accessToken,
      dblclick,
      activeKey,
      drawingsRef,
      draws,
      buttonclick,
      clampToGround,
      drawingsReadyDefault,
      drawEvt,
      newdata,
      // onLeftClick,
    };
  },
});
</script>

<style scoped lang="less">
.dt {
  position: absolute;
  top: 0;
  z-index: 12;
  width: 100%;
  height: 100%;
}
.index {
  z-index: 13;
  .ant-btn {
    margin-left: 10px;
  }
}
.z {
  z-index: 13;
  width: 200px;
}
.disno {
  display: none;
}
</style>
